<!-- 赞助排行榜 童晓白 2025-07-25 -->
<template>
  <view class="background"></view>
  <BackButton />
  <view class="container">
    <nav class="nav-links"></nav>

  <!-- 搜索框，图标在右侧 -->
    <view class="user-search-container">
      <input
        type="text"
        class="user-search-input"
      v-model="searchValue"
        placeholder="输入用户电话/邮箱/身份证/UID搜索"
      @focus="searchFocus = true"
      @blur="searchFocus = false"
    />
    <text class="material-icons user-search-icon">🔍</text>
    <view class="search-suggestions" v-if="searchFocus && searchSuggestions.length">
      <view class="suggestion-item" v-for="item in searchSuggestions" :key="item.id" @tap="selectSuggestion(item)">
        <image v-if="item.avatar" :src="item.avatar" class="suggestion-avatar" />
        <view class="suggestion-info">
          <view class="suggestion-name">{{ item.name }}</view>
          <view class="suggestion-details">
            <text class="suggestion-id">{{ item.id }}</text>
          </view>
        </view>
      </view>
    </view>
    </view>

    <view class="date-container">
      <text class="slogan">每一份支持，都是改变世界的温暖力量。感谢您的赞助，让爱与希望传递更远！ど⁰꒨⁰う♡</text>
      <!-- 按钮组，内容垂直居中 -->
      <view class="sponsor-actions">
        <button class="about-us-link" @click="goToAboutUs">
          <view class="btn-inner">
            <text class="about-us-text">关于我们</text>
          </view>
        </button>
      <button class="sponsor-btn" @tap="showSponsorModal = true">
          <view class="btn-inner">
            <text>我要赞助</text>
          </view>
        </button>
      <button class="test-banner-btn" @tap="testSponsorBanner">
          <view class="btn-inner">
            <text>测试横幅</text>
          </view>
        </button>
      <button class="history-btn last-btn" @tap="showHistoryModal = true">
          <view class="btn-inner">
            <text>赞助记录</text>
          </view>
        </button>
    </view>
    <view class="date-inputs">
      <!-- 微信小程序和H5通用的日期选择器，点击弹出原生日期选择器 -->
      <picker mode="date" :value="startDate" @change="onStartDateChange">
        <view class="date-input">{{ startDate || '开始日期' }}</view>
      </picker>
      <picker mode="date" :value="endDate" @change="onEndDateChange">
        <view class="date-input">{{ endDate || '结束日期' }}</view>
      </picker>
    </view>
      </view>

  <!-- 赞助弹窗 -->
  <view class="modal" v-if="showSponsorModal" @tap="closeSponsorModal">
        <view class="modal-content" @tap.stop>
          <view class="modal-header">
            <text>赞助支持</text>
        <button class="close-btn" @tap="showSponsorModal = false">&times;</button>
          </view>
          <view class="modal-body">
            <!-- 赞助类型选择 -->
            <view class="sponsor-type-section">
              <text class="section-title">赞助类型</text>
              <view class="sponsor-type-options">
                <button 
                  class="type-btn" 
                  :class="{ active: selectedSponsorType === 'PERSONAL' }"
                  @tap="selectedSponsorType = 'PERSONAL'"
                >
                  个人赞助
                </button>
                <button 
                  class="type-btn" 
                  :class="{ active: selectedSponsorType === 'ENTERPRISE' }"
                  @tap="selectedSponsorType = 'ENTERPRISE'"
                >
                  企业赞助
                </button>
                <button 
                  class="type-btn" 
                  :class="{ active: selectedSponsorType === 'ANONYMOUS' }"
                  @tap="selectedSponsorType = 'ANONYMOUS'"
                >
                  匿名赞助
                </button>
              </view>
            </view>
            
            <view class="amount-input">
              <text class="currency">¥</text>
          <input type="number" v-model.number="sponsorAmount" placeholder="请输入赞助金额" />
            </view>
            <view class="quick-amounts">
          <button class="amount-btn" @tap="sponsorAmount = 0.01">0.01元</button>
          <button class="amount-btn" @tap="sponsorAmount = 10">10元</button>
          <button class="amount-btn" @tap="sponsorAmount = 66">66元</button>
          <button class="amount-btn" @tap="sponsorAmount = 888">888元</button>
            </view>
            <view class="sponsor-progress">
              <view class="progress-bar">
                <view class="progress" style="width: 100%"></view>
              </view>
              <view class="progress-info"></view>
            </view>
            <button class="confirm-btn" @tap="confirmSponsor">确认赞助</button>
          </view>
        </view>
      </view>

  <!-- 历史记录弹窗 -->
  <view class="modal" v-if="showHistoryModal" @tap="closeHistoryModal">
        <view class="modal-content" @tap.stop>
          <view class="modal-header">
            <text>赞助记录</text>
        <button class="close-btn" @tap="showHistoryModal = false">&times;</button>
          </view>
          <view class="modal-body">
            <view class="filter-section">
              <view class="date-filter"></view>
              <view class="status-filter">
            <picker :range="statusOptions" :value="statusIndex" @change="onStatusChange"> 
              <view class="picker-text">{{ statusOptions[statusIndex] }}</view>
            </picker>
          </view>
        </view>
        <view class="record-list">
          <view class="record-item" v-for="record in historyList" :key="record.id">
            <view class="sponsor-info">
              <view class="sponsor-avatar">
                <image v-if="record.userAvatar" :src="record.userAvatar" alt="用户头像" class="avatar-image" />
                <text v-else>{{ record.nickname ? record.nickname.substring(0, 1) : '匿' }}</text>
              </view>
              <view class="sponsor-name">
                {{ record.nickname || '匿名用户' }}
                <text v-if="record.uid" class="org-name">(UID: {{ record.uid }})</text>
              </view>
            </view>
            <view class="sponsor-time">{{ record.sponsoredAt }}</view>
            <view class="sponsor-amount">¥{{ record.price }}</view>
          </view>
        </view>
            <view class="pagination">
          <button class="page-btn" :disabled="historyPage <= 1" @tap="historyPage--">上一页</button>
          <text class="page-info">第 {{ historyPage }} 页</text>
          <button class="page-btn" :disabled="historyPage >= historyTotalPage" @tap="historyPage++">下一页</button>
            </view>
          </view>
        </view>
      </view>

  <!-- 个人榜 top3 -->
  <view class="top3-podium">
    <view v-for="(item, idx) in top3Data" :key="item.uid || idx" :class="['podium-item', idx === 0 ? 'first' : idx === 1 ? 'second' : 'third']">
      <text class="crown">👑</text>
      <!-- 头像：如果有则显示，没有则显示占位符 -->
      <image v-if="getAvatarUrl(item.avatarUrl)" 
             :src="getAvatarUrl(item.avatarUrl)" 
             :alt="item.nickname + ' avatar'" 
             class="podium-avatar"
             @error="handleAvatarError" />
      <view v-else class="podium-avatar podium-avatar-placeholder">👤</view>
      <view class="podium-info">
        <text class="podium-name">{{ currentTab === 'personal' ? item.nickname : (item.companyName || item.name || item.nickname) }}</text>
        <text class="podium-amount">{{ formatMoney(item.amount) }}</text>
      </view>
      <text class="podium-number">{{ item.rank }}</text>
    </view>
  </view>

    <view class="tab-container">
    <button class="tab-button" :class="{active: currentTab === 'personal'}" @tap="switchTab('personal')">个人排行榜</button>
    <button class="tab-button" :class="{active: currentTab === 'enterprise'}" @tap="switchTab('enterprise')">企业排行榜</button>
    </view>

    <view class="ranking-list">
      <view class="ranking-list-header">
        <text class="ranking-list-th">排名</text>
        <text class="ranking-list-th">赞助者</text>
        <text class="ranking-list-th">赞助金额</text>
      </view>
      <!-- 正确渲染排行榜数据：排名、头像、昵称、金额 -->
      <view v-for="(row, idx) in rankingList" :key="row.uid || row.id || idx" :class="['ranking-list-row', idx < 3 ? 'top3' : '']" @click="goToUserProfile(row)">
        <text class="rank">{{ idx + 1 }}</text>
        <view class="avatar-wrapper">
          <image v-if="getAvatarUrl(row.avatarUrl)" 
                 :src="getAvatarUrl(row.avatarUrl)" 
                 class="avatar" 
                 @error="handleAvatarError" 
                 mode="aspectFill" />
          <view v-else class="avatar avatar-placeholder">👤</view>
          <text class="name">{{ row.nickname || row.name || row.companyName || '未知' }}</text>
        </view>
        <text class="amount">{{ formatMoney(row.amount) }}</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useUserStore } from '@/store/user'
import { NETWORK_CONFIG } from '@/config/network.js'
import BackButton from '@/components/BackButton.vue'

const searchValue = ref('')
const searchFocus = ref(false)
const searchSuggestions = ref([])

const showSponsorModal = ref(false)
const showHistoryModal = ref(false)
const sponsorAmount = ref(0.01)
const selectedSponsorType = ref('PERSONAL')
const startDate = ref('')
const endDate = ref('')
const currentTab = ref('personal')
const rankingList = ref([])
const top3Data = ref([])
const historyList = ref([])
const historyPage = ref(1)
const historyStatus = ref('success')
const historyTotalPage = ref(1)

const userStore = useUserStore()
const userInfo = reactive({
uid: '',
nickname: '',
avatarUrl: '',
amount: 0,
rank: 0
})

// 测试赞助横幅功能
const testSponsorBanner = () => {
  console.log('🎉 测试赞助横幅功能')
  
  // 模拟不同等级的赞助消息
  const testMessages = [
    { amount: 1, sponsorName: '测试用户1', sponsorType: '个人', level: 0 },
    { amount: 5, sponsorName: '测试用户2', sponsorType: '个人', level: 1 },
    { amount: 25, sponsorName: '测试用户3', sponsorType: '企业', level: 2 },
    { amount: 75, sponsorName: '测试用户4', sponsorType: '企业', level: 3 },
    { amount: 200, sponsorName: '测试用户5', sponsorType: '企业', level: 4 }
  ]
  
  // 随机选择一个测试消息
  const randomMessage = testMessages[Math.floor(Math.random() * testMessages.length)]
  console.log('🎉 选择的测试消息:', randomMessage)
  
  // 直接使用uni.showToast显示，和WebSocket消息通知一样的方式
  const sponsorText = `${randomMessage.sponsorName} 赞助了 ¥${randomMessage.amount} (${randomMessage.sponsorType})`
  const levelText = randomMessage.level ? ` - 等级${randomMessage.level}` : ''
  
  console.log('🎉 测试按钮开始显示Toast...')
  
  // 根据金额调整显示效果
  let toastTitle = sponsorText + levelText
  let toastIcon = 'success'
  let toastDuration = 3000
  
  if (randomMessage.amount >= 1000) {
    toastTitle = `🎉 ${toastTitle} 🎉`
    toastDuration = 5000
  } else if (randomMessage.amount >= 100) {
    toastTitle = `✨ ${toastTitle} ✨`
    toastDuration = 4000
  }
  
  // 三重播报测试：Toast + 炫酷横幅 + 原生通知
  console.log('🎉 测试三重播报显示')
  
  // 方式1：Toast播报
  uni.showToast({
    title: toastTitle,
    icon: toastIcon,
    duration: toastDuration,
    mask: false,
    position: 'top'
  })
  
  // 方式2：炫酷横幅播报
  try {
    const app = getApp()
    if (app && app.__SPONSOR_BANNER__) {
      console.log('🎉 测试使用炫酷横幅显示')
      app.__SPONSOR_BANNER__.showSponsorBanner(
        randomMessage.amount,
        randomMessage.sponsorName,
        randomMessage.sponsorType,
        randomMessage.level || 0,
        '',
        5000
      )
    } else {
      console.log('🎉 测试炫酷横幅未找到')
    }
  } catch (error) {
    console.log('🎉 测试获取炫酷横幅失败:', error)
  }
  
  // 方式3：原生通知播报
  try {
    const app = getApp()
    if (app && app.__NATIVE_NOTIFICATION__) {
      console.log('🎉 测试使用原生通知显示')
      if (randomMessage.level >= 4) {
        app.__NATIVE_NOTIFICATION__.showCombo(randomMessage)
      } else if (randomMessage.level >= 2) {
        app.__NATIVE_NOTIFICATION__.show(randomMessage)
        setTimeout(() => {
          app.__NATIVE_NOTIFICATION__.showLoading(randomMessage)
        }, 1000)
      } else {
        app.__NATIVE_NOTIFICATION__.show(randomMessage)
      }
    } else {
      console.log('🎉 测试原生通知未找到')
    }
  } catch (error) {
    console.log('🎉 测试获取原生通知失败:', error)
  }
  
  console.log('🎉 SP三重播报测试完成:', toastTitle)
  
  // 同时发送事件给组件（如果组件存在的话）
  const eventData = {
    type: 'sponsor_success',
    ...randomMessage,
    avatarUrl: 'https://tse1-mm.cn.bing.net/th/id/OIP-C.vJ3b6gPNCj0KqMQpgYx4egHaEK?w=295&h=180&c=7&r=0&o=5&dpr=2&pid=1.7'
  }
  
  uni.$emit('sponsor-success', eventData)
  console.log('🎉 测试完成')
}

onShow(async () => {
// 先清空 userInfo
Object.keys(userInfo).forEach(key => userInfo[key] = '')

const routeUid = uni.getStorageSync('routeUid')
const myUid = userStore.profile.uid

if (!routeUid || routeUid === myUid) {
  // 强制拉取自己的最新信息
  const token = uni.getStorageSync('accessToken')
  try {
    const res = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/user/me`,
      method: 'GET',
      header: { 'Access-Token': `Bearer ${token}` }
    })
    Object.assign(userInfo, res.data)
    // 如果你有 userStore.profile，也同步更新
    Object.assign(userStore.profile, res.data)
  } catch (e) {
    console.error('获取本人信息失败', e)
  }
  uni.removeStorageSync('routeUid')
} else {
  // 拉取他人信息
  try {
    const token = uni.getStorageSync('accessToken')
    const res = await uni.request({
      url: '${NETWORK_CONFIG.API_BASE_URL}/user/info',
      method: 'POST',
      data: { uid: routeUid },
      header: { 'Access-Token': `Bearer ${token}` }
    })
    Object.assign(userInfo, res.data)
  } catch (error) {
    console.error('加载他人用户信息失败', error)
  }
  uni.removeStorageSync('routeUid')
}
})

// 搜索建议逻辑（可根据实际接口实现）
watch(searchValue, async (val) => {
if (!val) {
  searchSuggestions.value = []
  return
}
// TODO: 调用后端接口获取建议
// searchSuggestions.value = await fetchSuggestions(val)
searchSuggestions.value = []
})

function goToAboutUs() {
uni.navigateTo({ url: '/pages/aboutour/index' })
}

function selectSuggestion(item) {
searchValue.value = item.name
searchSuggestions.value = []
}

function formatMoney(amount) {
if (!amount) return '￥0.00'
// 保证是数字
let num = Number(amount)
// 千分位格式化
return '￥' + num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

function switchTab(tab) {
currentTab.value = tab
fetchRanking()
}

async function fetchRanking() {
  // type: 1=个人, 2=企业
const type = currentTab.value === 'personal' ? '1' : '2'
let url = `${NETWORK_CONFIG.API_BASE_URL}/sponsors?type=${type}`;
const today = new Date();
const yyyy = today.getFullYear();
const mm = String(today.getMonth() + 1).padStart(2, '0');
const dd = String(today.getDate()).padStart(2, '0');
const defaultStart = `${yyyy}-01-01`;
const defaultEnd = `${yyyy}-${mm}-${dd}`;
url += `&startDate=${startDate.value || defaultStart}`;
url += `&endDate=${endDate.value || defaultEnd}`;
try {
  // 添加Access-Token header
  const token = uni.getStorageSync('accessToken');
  const header = {};
  if (token) {
    header['Access-Token'] = `Bearer ${token}`;
  }
  
  const res = await uni.request({ 
    url, 
    method: 'GET',
    header
  })
  const data = res.data
  console.log('赞助排行榜原始数据:', data)
  
  if (data) {
    const rankingArr = Object.entries(data).map(([jsonInfo, amount], idx) => {
      let info = {};
      try {
        info = JSON.parse(jsonInfo)
        console.log(`解析后的第${idx+1}条信息:`, info)
        console.log(`  - nickname:`, info.nickname)
        console.log(`  - avatarUrl:`, info.avatarUrl)
        console.log(`  - uid:`, info.uid)
      } catch (e) {
        console.error('解析JSON失败:', jsonInfo, e)
        info = { nickname: jsonInfo };
      }
      return {
        ...info,
        amount,
        rank: idx + 1
      }
    })
    console.log('最终排行榜数组:', rankingArr)
    rankingList.value = rankingArr
    
    // 获取前三名数据
    const top3 = rankingArr.slice(0, 3)
    console.log('前三名数据:', top3)
    top3.forEach((item, idx) => {
      console.log(`第${idx+1}名 - nickname:`, item.nickname, ', avatarUrl:', item.avatarUrl, ', uid:', item.uid)
      console.log(`  处理后头像URL:`, getAvatarUrl(item.avatarUrl))
    })
    top3Data.value = top3
  }
} catch (e) {
  uni.showToast({ title: '获取排行榜失败', icon: 'none' })
}
}

async function confirmSponsor() {
if (!sponsorAmount.value || sponsorAmount.value < 0.01 || sponsorAmount.value > 100000) {
  uni.showToast({ title: '请输入有效金额（0.01-100000元）', icon: 'none' })
  return
}

try {
  uni.showLoading({ title: '创建订单中...' })
  
  // 获取用户真实openId
  let openId = ''
  try {
    console.log('=== 开始获取用户openId ===')
    console.log('当前环境:', uni.getSystemInfoSync().platform)
    console.log('当前小程序版本:', uni.getSystemInfoSync().version)
    
    // 清除可能过期的openId缓存，确保获取最新的openId
    console.log('🔄 清除可能过期的openId缓存...')
    uni.removeStorageSync('user_openid')
    
    // 直接获取最新的openId，不使用缓存
    console.log('🔄 开始获取最新openId...')
    
    // 通过wx.login获取code，然后调用后端获取openId
    console.log('开始调用uni.login()...')
    
    // 先检查用户授权状态
    const authSetting = await uni.getSetting()
    console.log('用户授权设置:', authSetting.authSetting)
    
    // 检查并请求必要的授权
    if (!authSetting.authSetting['scope.userInfo']) {
      console.log('用户未授权，开始请求授权...')
      try {
        const authRes = await uni.authorize({
          scope: 'scope.userInfo'
        })
        console.log('授权结果:', authRes)
      } catch (authError) {
        console.log('授权失败，用户拒绝授权:', authError)
        // 如果用户拒绝授权，引导用户手动开启
        uni.showModal({
          title: '需要授权',
          content: '为了完成支付，需要获取您的微信授权信息，请在设置中开启',
          showCancel: false,
          success: () => {
            uni.openSetting()
          }
        })
        throw new Error('用户拒绝授权')
      }
    }
    
    // 获取用户信息
    let userInfo = null
    try {
      userInfo = await uni.getUserInfo()
      console.log('获取用户信息成功:', userInfo)
    } catch (userError) {
      console.log('获取用户信息失败:', userError)
      // 如果获取用户信息失败，仍然可以继续支付流程
    }
    
    const loginRes = await uni.login({
      provider: 'weixin'
    })
      console.log('uni.login()结果:', loginRes)
      console.log('loginRes.code:', loginRes.code)
      console.log('loginRes.errMsg:', loginRes.errMsg)
      
      if (loginRes.code) {
        console.log('✅ 获取到code，开始调用后端接口')
        console.log('code长度:', loginRes.code.length)
        console.log('code格式:', loginRes.code)
        
        // 调用后端接口获取openId
        const openIdRes = await uni.request({
          url: '${NETWORK_CONFIG.API_BASE_URL}/sponsors/get-openid',
          method: 'POST',
          data: {
            code: loginRes.code
          },
          header: {
            'Authorization': 'Bearer ' + uni.getStorageSync('token')
          }
        })
        
        console.log('=== 后端openId接口响应 ===')
        console.log('响应状态码:', openIdRes.statusCode)
        console.log('响应数据:', openIdRes.data)
        console.log('响应头:', openIdRes.header)
        
        if (openIdRes.data && openIdRes.data.success && openIdRes.data.openid) {
          openId = openIdRes.data.openid
          console.log('✅ 获取到真实openId:', openId)
          console.log('openId长度:', openId.length)
          console.log('openId格式检查:', /^[a-zA-Z0-9_-]{28}$/.test(openId) ? '格式正确' : '格式异常')
          console.log('openId是否以wx_开头:', openId.startsWith('wx_'))
          
          // 缓存openId
          uni.setStorageSync('user_openid', openId)
          console.log('✅ openId已缓存到本地存储')
        } else {
          console.log('❌ 后端返回无效openId')
          console.log('success字段:', openIdRes.data?.success)
          console.log('openid字段:', openIdRes.data?.openid)
          console.log('message字段:', openIdRes.data?.message)
          
          // 如果是模拟openid，清除缓存并重试
          if (openIdRes.data?.openid && openIdRes.data.openid.startsWith('wx_')) {
            console.log('检测到模拟openid，清除缓存并重试...')
            uni.removeStorageSync('user_openid')
            // 可以在这里添加重试逻辑
          }
          
          throw new Error('获取openId失败: ' + (openIdRes.data?.message || '未知错误'))
        }
      } else {
        console.log('❌ uni.login()失败')
        console.log('errMsg:', loginRes.errMsg)
        throw new Error('wx.login失败: ' + loginRes.errMsg)
      }
  } catch (e) {
    console.error('=== 获取openId异常详情 ===')
    console.error('异常类型:', e.name || 'Unknown')
    console.error('异常信息:', e.message)
    console.error('异常堆栈:', e.stack)
    console.error('完整异常对象:', e)
    
    uni.showToast({ 
      title: '获取用户信息失败，请重试', 
      icon: 'none',
      duration: 3000
    })
    return
  }
  
  if (!openId) {
    uni.showToast({ 
      title: '无法获取用户信息，请重新登录', 
      icon: 'none',
      duration: 3000
    })
    return
  }
  
  // 使用选择的赞助类型
  const sponsorType = selectedSponsorType.value
  
  // 根据赞助类型设置type值
  let type = 1; // 默认个人
  if (sponsorType === 'ANONYMOUS') {
    type = 0;
  } else if (sponsorType === 'PERSONAL') {
    type = 1;
  } else if (sponsorType === 'ENTERPRISE') {
    type = 2;
  }
  
  // 调用后端创建订单接口
  const token = uni.getStorageSync('accessToken')
  
  // 调试信息：打印请求参数
  console.log('=== 创建订单调试信息 ===')
  console.log('请求URL:', '${NETWORK_CONFIG.API_BASE_URL}/sponsors/create-order')
  console.log('Token:', token ? '已获取' : '未获取')
  console.log('请求参数:', {
    amount: sponsorAmount.value,
    type: type,
    remark: '用户赞助',
    openId: openId
  })
  
  const res = await uni.request({
    url: '${NETWORK_CONFIG.API_BASE_URL}/sponsors/create-order',
    method: 'POST',
    header: { 
      'Access-Token': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    data: {
      amount: sponsorAmount.value,
      type: type,
      remark: '用户赞助',
      openId: openId
    }
  })
  
  // 调试信息：打印响应结果
  console.log('响应状态码:', res.statusCode)
  console.log('响应数据:', res.data)
  console.log('响应头:', res.header)
  
  uni.hideLoading()
  
  if (res.data && res.data.success) {
    showSponsorModal.value = false
    
    // 调用微信支付
    try {
      const payParams = res.data.payParams
      console.log('=== 前端支付参数调试 ===')
      console.log('支付参数:', payParams)
      console.log('timeStamp:', payParams.timeStamp, '类型:', typeof payParams.timeStamp)
      console.log('nonceStr:', payParams.nonceStr, '类型:', typeof payParams.nonceStr)
      console.log('package:', payParams.package, '类型:', typeof payParams.package)
      console.log('signType:', payParams.signType, '类型:', typeof payParams.signType)
      console.log('paySign:', payParams.paySign, '类型:', typeof payParams.paySign)
      console.log('appId:', payParams.appId, '类型:', typeof payParams.appId)
      
      // 确保参数类型正确
      const paymentParams = {
        provider: 'wxpay',
        timeStamp: String(payParams.timeStamp),
        nonceStr: String(payParams.nonceStr),
        package: String(payParams.package),
        signType: String(payParams.signType),
        paySign: String(payParams.paySign)
      }
      
      console.log('=== 转换后的支付参数 ===')
      console.log('转换后参数:', paymentParams)
      
      const payRes = await uni.requestPayment(paymentParams)
      console.log('支付结果:', payRes)
      
      // 支付成功
      uni.showToast({ title: '赞助成功！', icon: 'success' })
      // 刷新排行榜
      fetchRanking()
      
    } catch (payError) {
      console.error('=== 支付错误详情 ===')
      console.error('支付错误:', payError)
      console.error('错误信息:', payError.errMsg)
      console.error('错误代码:', payError.errCode)
      
      if (payError.errMsg && payError.errMsg.includes('cancel')) {
        uni.showToast({ title: '支付已取消', icon: 'none' })
      } else if (payError.errMsg && payError.errMsg.includes('sign')) {
        uni.showToast({ title: '支付签名验证失败，请重试', icon: 'none' })
      } else {
        uni.showToast({ title: '支付失败：' + (payError.errMsg || '未知错误'), icon: 'none' })
      }
    }
  } else {
    // 调试信息：打印失败原因
    console.log('订单创建失败:', res.data)
    const errorMsg = res.data?.message || res.data?.error || '创建订单失败'
    console.log('错误信息:', errorMsg)
    uni.showToast({ title: errorMsg, icon: 'none' })
  }
} catch (e) {
  uni.hideLoading()
  console.error('=== 赞助异常信息 ===')
  console.error('异常类型:', e.name || 'Unknown')
  console.error('异常信息:', e.message)
  console.error('异常堆栈:', e.stack)
  console.error('完整异常对象:', e)
  
  // 更详细的错误信息
  let errorMsg = '系统错误，请稍后重试'
  if (e.message) {
    errorMsg = e.message
  } else if (e.errMsg) {
    errorMsg = e.errMsg
  }
  
  uni.showToast({ title: errorMsg, icon: 'none' })
}
}

async function fetchHistory() {
try {
  uni.showLoading({ title: '加载中...' })
  // TODO: 调用后端接口获取历史记录
  // const res = await uni.request({ url: `${NETWORK_CONFIG.API_BASE_URL}/sponsorships?page=${historyPage.value-1}&size=10` })
  // historyList.value = res.data.content || []
  // historyTotalPage.value = Math.ceil(res.data.totalElements / 10)
  historyList.value = []
  historyTotalPage.value = 1
  uni.hideLoading()
        } catch (e) {
  uni.hideLoading()
  uni.showToast({ title: '加载记录失败', icon: 'none' })
}
}

watch([showHistoryModal, historyPage], ([show, page]) => {
if (show) fetchHistory()
})

    onMounted(() => {
const today = new Date();
const yyyy = today.getFullYear();
const mm = String(today.getMonth() + 1).padStart(2, '0');
const dd = String(today.getDate()).padStart(2, '0');
const startDate = ref(`${yyyy}-01-01`);
const endDate = ref(`${yyyy}-${mm}-${dd}`);
fetchRanking()
})

const statusOptions = ['支付成功']
const statusIndex = ref(0)
function onStatusChange(e) {
statusIndex.value = e.detail.value
// 如果你需要 historyStatus 变量
historyStatus.value = statusOptions[statusIndex.value]
}

// 日期选择器事件，兼容微信小程序和H5
function onStartDateChange(e) {
startDate.value = e.detail.value
fetchRanking()
}
function onEndDateChange(e) {
endDate.value = e.detail.value
fetchRanking()
}

function closeSponsorModal() {
showSponsorModal.value = false
}
function closeHistoryModal() {
showHistoryModal.value = false
}

// 获取头像URL
function getAvatarUrl(avatar) {
  // 如果没有头像，直接返回默认值
  if (!avatar || avatar === 'null' || avatar === 'undefined' || avatar === '') {
    return ''
  }
  // 如果已经是完整URL，直接返回
  if (avatar.startsWith('http') || avatar.startsWith('data:')) {
    return avatar
  }
  // 如果是相对路径，拼接完整URL
  if (avatar.startsWith('/uploads')) {
    return `${NETWORK_CONFIG.API_BASE_URL}${avatar}`
  }
  return avatar
}

// 头像加载失败处理
function handleAvatarError(e) {
  console.error('头像加载失败，使用默认头像')
  // 不做任何操作，让getAvatarUrl处理默认值
}

// 跳转到用户主页
function goToUserProfile(row) {
  const uid = row.uid || row.id
  if (!uid) {
    uni.showToast({ title: '用户信息缺失', icon: 'none' })
    return
  }
  
  uni.navigateTo({
    url: `/pages/profile/index?uid=${uid}`,
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({ title: '页面跳转失败', icon: 'none' })
    }
  })
}
</script>

<style scoped>
.background {
position: fixed;
top: 0; left: 0;
width: 100vw;
height: 100vh;
z-index: -1;
background: linear-gradient(135deg, #e0e7ff 0%, #fce4ec 100%);
}
.container {
width: 100vw;
min-height: 100vh;
margin: 0 auto;
padding: 0 0 32px 0;
background: transparent;
position: relative;
overflow-x: hidden;
display: flex;
flex-direction: column;
align-items: center;
box-sizing: border-box;
padding-left: 4vw;
padding-right: 4vw;
max-width: 100vw;
}
/* 搜索框外层容器，横向排列，图标在右侧 */
.user-search-container {
width: 100%;
max-width: 340px;
margin: 10px auto 6px auto;
border: 1.5px solid #4A90E2;
border-radius: 18px;
background: #fff;
display: flex;
align-items: center;
box-shadow: 0 2px 8px rgba(74,144,226,0.04);
height: 36px;
}
/* 搜索输入框，填满剩余空间，圆角，字体大小，左右内边距 */
.user-search-input {
flex: 1;
border: none;
outline: none;
font-size: 15px;
background: transparent;
padding: 0 10px;
height: 36px;
border-radius: 18px;
}
/* 搜索图标，放在右侧，主题色，左侧间距 */
.material-icons.user-search-icon {
margin-left: 8px;
color: #4A90E2;
font-size: 20px;
}
.search-suggestions {
position: absolute;
top: 110%;
left: 0;
width: 100%;
background: #fff;
border: 1px solid #eee;
border-radius: 12px;
max-height: 200px;
overflow-y: auto;
z-index: 100;
box-shadow: 0 4px 16px rgba(74,144,226,0.08);
}
.suggestion-item {
display: flex;
align-items: center;
padding: 10px 15px;
cursor: pointer;
border-bottom: 1px solid #f3f3f3;
font-size: 14px;
}
.suggestion-avatar {
width: 28px;
height: 28px;
border-radius: 50%;
margin-right: 10px;
object-fit: cover;
}
.suggestion-info {
flex-grow: 1;
}
.suggestion-name {
font-weight: 600;
color: #333;
}
.suggestion-details {
font-size: 0.8em;
color: #666;
}
.date-container {
width: 100vw;
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
gap: 6px;
margin-bottom: 8px;
}
/* 标语，主题色加粗，居中，字号适中，行高适中 */
.slogan {
color: #7c3aed;
font-weight: bold;
font-size: 15px;
text-align: center;
margin: 8px 0 0 0;
line-height: 1.5;
}
/* 按钮组，横向排列，间距12px，防止重叠 */
.sponsor-actions {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
margin: 12px 0 8px 0;
}
/* 主按钮基础样式，均分宽度，最小宽度限制，圆角更大，字体加粗，字号适中，内容水平垂直居中 */
.sponsor-btn, .about-us-link, .history-btn, .test-banner-btn {
flex: 1 1 0;
min-width: 90px;
max-width: 100%;
padding: 0 10px;
border-radius: 22px;
font-weight: bold;
font-size: 16px;
display: flex;
align-items: center;
justify-content: center;
height: 40px;
line-height: 40px;
border: none;
margin: 0;
background: #4A90E2;
color: #fff;
box-shadow: 0 2px 8px rgba(74,144,226,0.08);
transition: background 0.2s;
}
/* 按钮内容内层，flex居中，保证文字始终垂直水平居中 */
.btn-inner {
width: 100%;
display: flex;
align-items: center;
justify-content: center;
}
/* 移除按钮间多余外边距，防止被压缩 */
.sponsor-actions > button {
margin: 0;
}
/* 小屏下字体和内边距适配，防止内容溢出 */
@media (max-width: 400px) {
.sponsor-btn, .about-us-link, .history-btn {
  font-size: 14px;
  padding: 0 4px;
}
}
/* 不同按钮的渐变色 */
.sponsor-btn { background: #4A90E2; }
.history-btn { background: #4A90E2; }
.about-us-link { background: #4A90E2;}
.test-banner-btn { background: #9C27B0; }

/* 按钮内图标与文字间距 */
.btn-inner .iconfont {
margin-right: 6px;
}
.first-btn { margin-left: 0; }
.last-btn { margin-right: 0; }
/* 日期输入区，横向排列，间距8px，居中 */
.date-inputs {
display: flex;
gap: 8px;
justify-content: center;
margin: 8px 0 0 0;
width: 100%;
max-width: 340px;
}
/* 日期输入框，圆角，主题色边框，统一高度，居中显示 */
.date-input {
flex: 1;
border: 1.5px solid #4A90E2;
border-radius: 18px;
font-size: 15px;
height: 36px;
background: #fff;
padding: 0 10px;
text-align: center;
display: flex;
align-items: center;
justify-content: center;
}

/* tab切换区，横向排列，紧贴无间隙，顶部圆角 */
.tab-container {
display: flex;
justify-content: center;
gap: 0;
margin: 18px 0 8px 0;
width: 100%;
max-width: 340px;
}
/* tab按钮，未选中灰色，选中渐变色，顶部圆角 */
.tab-button {
flex: 1 1 0;
padding: 0;
height: 38px;
line-height: 38px;
border: none;
border-radius: 18px 18px 0 0;
font-size: 15px;
font-weight: bold;
color: #fff;
background: #bdbdbd;
transition: background 0.2s;
}
.tab-button.active {
background: #4A90E2;
color: #fff;
}
.top3-podium {
display: flex;
justify-content: center;
align-items: flex-end;
gap: 6px;
margin: 10px 0 6px 0;
width: 100%;
max-width: 340px;
}
.podium-item {
background: #fff;
border-radius: 18px;
box-shadow: 0 4px 16px rgba(74,144,226,0.10);
padding: 8px 4px 12px 4px;
text-align: center;
width: 70px;
position: relative;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-end;
}
.podium-item.first {
width: 90px;
z-index: 2;
background: linear-gradient(135deg, #fffbe6 60%, #ffe4e1 100%);
box-shadow: 0 8px 24px rgba(255,215,0,0.13);
}
.podium-item.second {
width: 70px;
z-index: 1;
background: linear-gradient(135deg, #f3f3f3 60%, #e0e0e0 100%);
}
.podium-item.third {
width: 70px;
z-index: 1;
background: linear-gradient(135deg, #fbeee6 60%, #f5d6c6 100%);
}
.crown {
font-size: 18px;
margin-bottom: 2px;
}
.podium-avatar {
width: 32px;
height: 32px;
border-radius: 50%;
border: 2px solid #fff;
margin: 0 auto 4px auto;
object-fit: cover;
box-shadow: 0 2px 8px rgba(74,144,226,0.10);
}
.podium-avatar-placeholder {
background: linear-gradient(135deg, #f0f0f0 0%, #e0e0e0 100%);
color: #999;
font-size: 18px;
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 2px 8px rgba(74,144,226,0.10);
}
.podium-info {
text-align: center;
margin-top: 0;
color: #2c3e50;
font-size: 13px;
}
.podium-name {
font-weight: bold;
font-size: 13px;
margin-bottom: 2px;
}
.podium-amount {
font-size: 13px;
color: #e74c3c;
font-weight: bold;
}
.podium-number {
position: absolute;
bottom: 4px;
right: 6px;
font-size: 11px;
color: #e0e0e0;
font-weight: bold;
}
/* 排行榜表头，主题色背景，圆角，字体加粗 */
.ranking-list {
width: 100%;
max-width: 340px;
background: #fff;
border-radius: 14px;
box-shadow: 0 4px 16px rgba(74,144,226,0.10);
overflow: hidden;
margin: 0 auto 12px auto;
display: flex;
flex-direction: column;
}
/* 表头单元格，居中 */
.ranking-list-header {
display: flex;
flex-direction: row;
background: #4A90E2;
color: #fff;
font-size: 15px;
font-weight: 700;
padding: 10px 0;
border-radius: 12px 12px 0 0;
margin-bottom: 0;
}
/* 表头单元格，居中 */
.ranking-list-th {
flex: 1 1 0;
text-align: center;
}
.ranking-list-row {
display: flex;
flex-direction: row;
align-items: center;
font-size: 12px;
border-bottom: 1px solid #f3f3f3;
padding: 7px 0;
cursor: pointer;
transition: background-color 0.2s;
}
.ranking-list-row:active {
background-color: #f5f5f5;
}
.rank {
flex: 1 1 0;
text-align: center;
font-weight: bold;
}
.avatar-wrapper {
flex: 1 1 0;
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
}
.avatar {
width: 24px;
height: 24px;
border-radius: 50%;
object-fit: cover;
border: 1.5px solid #e0e0e0;
}
.avatar-placeholder {
display: flex;
align-items: center;
justify-content: center;
background-color: #f0f0f0;
color: #999;
font-size: 14px;
}
.name {
font-size: 12px;
color: #2c3e50;
font-weight: 600;
margin-left: 2px;
}
.amount {
flex: 1 1 0;
text-align: center;
font-weight: bold;
color: #e74c3c;
}
.sponsor-info {
display: flex;
align-items: center;
gap: 6px;
}
.sponsor-avatar {
width: 24px;
height: 24px;
border-radius: 50%;
background: #f356a4;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: bold;
font-size: 12px;
}
.sponsor-avatar .avatar-image {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 50%;
}
.sponsor-name {
font-weight: 600;
color: #2c3e50;
font-size: 12px;
}
.sponsor-time {
color: #6c757d;
font-size: 10px;
}
.sponsor-amount {
font-weight: 600;
color: #f356a4;
font-size: 12px;
padding: 2px 6px;
background: #fce4ec;
border-radius: 10px;
}
.modal {
display: flex;
align-items: center;
justify-content: center;
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: #0008;
z-index: 1000;
opacity: 1;
}
.modal-content {
background: #fff;
border-radius: 18px;
width: 92vw;
max-width: 420px;
margin: auto;
padding: 24px 18px 18px 18px;
display: flex;
flex-direction: column;
align-items: center;
box-shadow: 0 8px 32px rgba(74,144,226,0.13);
position: relative;
}
.close-btn {
position: absolute;
right: 18px;
top: 18px;
width: 32px;
height: 32px;
border: none;
background: transparent;
color: #6c757d;
font-size: 24px;
border-radius: 50%;
transition: background 0.2s;
}
.sponsor-type-section {
width: 100%;
margin: 10px 0 15px 0;
}
.section-title {
display: block;
font-size: 16px;
font-weight: bold;
color: #333;
margin-bottom: 10px;
text-align: center;
}
.sponsor-type-options {
  display: flex;
  gap: 8px;
  justify-content: center;
  flex-wrap: wrap;
}
.type-btn {
  flex: 1;
  min-width: 80px;
  padding: 10px 8px;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  background: #fff;
  color: #666;
  font-size: 13px;
  font-weight: 600;
  transition: all 0.2s;
  text-align: center;
}
.type-btn.active {
border-color: #4A90E2;
background: #4A90E2;
color: #fff;
}
.amount-input {
width: 100%;
display: flex;
align-items: center;
justify-content: center;
margin: 18px 0 10px 0;
}
.amount-input input {
width: 70%;
padding: 12px 12px 12px 30px;
border: 1.5px solid #e0e0e0;
border-radius: 16px;
font-size: 18px;
background: #f7faff;
}
.currency {
position: absolute;
left: 24px;
color: #eb48b2;
font-size: 18px;
}
.quick-amounts {
display: flex;
gap: 10px;
margin: 10px 0 18px 0;
width: 100%;
justify-content: center;
}
.amount-btn {
flex: 1 1 0;
padding: 10px 0;
border: none;
border-radius: 14px;
background: #f7f7ff;
color: #f356a4;
font-weight: 600;
font-size: 15px;
box-shadow: 0 1px 4px rgba(243,86,164,0.04);
transition: background 0.2s;
}
.confirm-btn {
width: 100%;
padding: 13px 0;
background: linear-gradient(90deg, #3498db 60%, #a36be6 100%);
color: white;
border: none;
border-radius: 18px;
font-size: 17px;
font-weight: bold;
margin-top: 10px;
box-shadow: 0 2px 8px rgba(74,144,226,0.08);
transition: background 0.2s;
}
.filter-section {
display: flex;
gap: 10px;
margin-bottom: 10px;
flex-wrap: wrap;
justify-content: center;
}
.status-filter {
min-width: 120px;
}
.picker-text {
color: #4A90E2;
font-weight: bold;
font-size: 15px;
padding: 8px 0;
text-align: center;
}
.record-list {
margin: 10px 0;
max-height: 260px;
overflow-y: auto;
padding: 0 2px;
}
.record-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 8px;
margin: 6px 0;
background: #f7faff;
border-radius: 12px;
box-shadow: 0 1px 4px rgba(74,144,226,0.04);
font-size: 13px;
}
.pagination {
padding: 10px 0 0 0;
display: flex;
justify-content: center;
align-items: center;
gap: 16px;
background: none;
border-radius: 12px;
}
.page-btn {
padding: 7px 18px;
border: none;
border-radius: 12px;
background: #e0e7ff;
color: #4A90E2;
font-size: 14px;
font-weight: 600;
transition: background 0.2s;
}
.page-info {
color: #4A90E2;
font-size: 14px;
font-weight: bold;
letter-spacing: 1px;
}
</style>